﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace DontForgetISaw
{
    public partial class StartForm : Form
    {
        public StartForm()
        {
            InitializeComponent();
        }

        private void initRootDir()
        {
            string appPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), Const.AppCategoryName);
            if (!Directory.Exists(appPath))
            {
                Directory.CreateDirectory(appPath);
            }
            string confFile = Path.Combine(appPath, Const.ConfFileName);
            if (File.Exists(confFile))
            {
                using (StreamReader reader = new StreamReader(confFile))
                {
                    string lastUserPath = reader.ReadLine();
                    if (!string.IsNullOrEmpty(lastUserPath))
                    {
                        this.textBox1.Text = lastUserPath;
                    }
                }
            }
        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            this.saveLastUserPath();
            TreeNode node = this.treeView1.SelectedNode;
            if (node.Tag is DirectoryInfo)
            {
                showNewFile(((DirectoryInfo)node.Tag));
            }
            else if (node.Tag is TreeNodeTag)
            {
                showNewFile(((TreeNodeTag)node.Tag).Dir);
            }
            else if (node.Tag is FileInfo)
            {
                showFile(node.Tag as FileInfo);
            }
        }
        private void btnBrowse_Click(object sender, EventArgs e)
        {
            using (FolderBrowserDialog dialog = new FolderBrowserDialog())
            {
                if (dialog.ShowDialog() == DialogResult.OK)
                {
                    string path = dialog.SelectedPath;
                    this.textBox1.Text = path;
                }
            }
        }


        private void showNewFile(DirectoryInfo parentDir)
        {
            DateTime dt = DateTime.Now;
            string fileBasePath = Path.Combine(parentDir.FullName, dt.Year + "-" + dt.Month + "-" + dt.Day);

            string fileFullName = fileBasePath + Const.FileExt;

            int index = 1;
            while (File.Exists(fileFullName))
            {
                fileFullName = fileBasePath + "." + index + Const.FileExt;
                ++index;
            }
            FileInfo newFile = new FileInfo(fileFullName);
            showFile(newFile);
        }

        private void showFile(FileInfo fileInfo)
        {
            ContentForm contentForm = new ContentForm();
            contentForm.File = fileInfo;
            this.Hide();
            contentForm.ShowDialog();
            this.Close();
        }

        private void saveLastUserPath()
        {
            string appPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), Const.AppCategoryName);
            if (!Directory.Exists(appPath))
            {
                Directory.CreateDirectory(appPath);
            }
            string confFile = Path.Combine(appPath, Const.ConfFileName);
            using (StreamWriter writer = new StreamWriter(confFile))
            {
                writer.Write(this.textBox1.Text);
            }
        }


        private void expandTreeNode(TreeNodeCollection parent, DirectoryInfo directory)
        {
            DirectoryInfo[] dirs = directory.GetDirectories();
            foreach (DirectoryInfo dir in dirs)
            {
                TreeNode node = new TreeNode();
                node.SelectedImageIndex = 0;
                node.ImageIndex = 0;
                node.Text = dir.Name;
                node.Tag = new TreeNodeTag(dir);
                node.Nodes.Add(new TreeNode("...", 0, 0));
                parent.Add(node);
            }
            FileInfo[] files = directory.GetFiles();
            foreach (FileInfo file in files)
            {
                string extension = file.Extension;
                if (string.Equals(extension, Const.FileExt))
                {
                    TreeNode node = new TreeNode();
                    node.SelectedImageIndex = 1;
                    node.ImageIndex = 1;
                    node.Text = file.Name;
                    node.Tag = file;
                    parent.Add(node);
                }

            }
        }

        private void treeView1_BeforeExpand(object sender, TreeViewCancelEventArgs e)
        {
            TreeNode node = e.Node;
            if (node.Tag is TreeNodeTag)
            {
                node.Nodes.Clear();
                TreeNodeTag tag = node.Tag as TreeNodeTag;
                tag.Expanded = true;
                node.Tag = tag.Dir;
                expandTreeNode(node.Nodes, tag.Dir);
            }
        }


        private class TreeNodeTag
        {
            public TreeNodeTag(DirectoryInfo dir)
            {
                this.dir = dir;
            }
            private bool expanded = false;
            private DirectoryInfo dir;

            public DirectoryInfo Dir { get => dir; set => dir = value; }
            public bool Expanded { get => expanded; set => expanded = value; }
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            string path = this.textBox1.Text;
            if (!Directory.Exists(path))
            {
                MessageBox.Show("目录不存在");
            }
            else
            {
                this.textBox1.Text = path;
                treeView1.Nodes.Clear();
                DirectoryInfo directory = new DirectoryInfo(path);
                TreeNode rootNode = new TreeNode(directory.Name, 0, 0)
                {
                    Tag = directory
                };
                treeView1.Nodes.Add(rootNode);
                expandTreeNode(rootNode.Nodes, directory);
                treeView1.SelectedNode = rootNode;
            }
        }

        private void StartForm_Shown(object sender, EventArgs e)
        {
            this.initRootDir();
        }

        private void treeView1_NodeMouseDoubleClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            if (e.Node.Tag is FileInfo)
            {
                this.btnOK_Click(sender, e);
            }
        }

        private void StartForm_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.O && e.Control)
            {
                this.btnBrowse_Click(sender, e);
            }
            else if (e.KeyCode == Keys.O && e.Alt)
            {
                this.btnOK_Click(sender, e);
            }
        }
    }
}
